package com.jhws.business.comm.service;

import com.jhws.business.comm.bo.TblBuildingDimBo;
import com.jhws.business.comm.bo.TblCommDimBo;
import com.jhws.business.owner.bo.OwnerConstant;
import com.jhws.sys.user.bo.TblUserDimBo;
import com.jhws.business.device.bo.UserDevice;
import com.jhws.common.base.bo.Global;
import com.jhws.common.Page;
import com.jhws.core.db.BaseDao;
import com.jhws.business.comm.dao.ITblCommDimDAO;
import com.jhws.sys.user.service.ITblUserDimService;
import com.jhws.sys.user.service.UserCommsService;
import com.jhws.util.AccountsUtils;
import com.jhws.util.commUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TblCommDimServiceSpringImpl implements ITblCommDimService {
    @Resource
    private BaseDao BaseDao;
    @Resource
    protected ITblUserDimService IUserService;
    @Resource
    protected UserCommsService userCommsService;
    @Resource
    protected ITblBuildingDimService IBuildingService;
    private ITblCommDimDAO tblCommDimDAO;


    public ITblCommDimDAO getTblCommDimDAO() {
        return tblCommDimDAO;
    }

    public void setTblCommDimDAO(ITblCommDimDAO tblCommDimDAO) {
        this.tblCommDimDAO = tblCommDimDAO;
    }


    public Page findTblCommDim(int start, int num, String whereClause)
            throws Exception {
        Page page = tblCommDimDAO.findTblCommDim(start, num, whereClause);
        return page;
    }


    public TblCommDimBo save(TblCommDimBo bo) throws Exception {
        return tblCommDimDAO.save(bo);
    }

    public TblCommDimBo merge(TblCommDimBo bo) throws Exception {
        return tblCommDimDAO.merge(bo);
    }

    public List<TblCommDimBo> findTblCommDimByWhere(String whereClause) throws Exception {
        return tblCommDimDAO.findTblCommDimByWhere(whereClause);
    }

    public TblCommDimBo findTblCommDimById(String TblCommId) {
        return tblCommDimDAO.getById(TblCommId);
    }

    @Override
    public TblCommDimBo findTblCommDimByCommCode(String commCode) throws Exception {
        List<TblCommDimBo> commDimBoList = tblCommDimDAO.findTblCommDimByWhere("where 1=1 and comm_code = '" + commCode + "'");
        if (commDimBoList.size() > 0) {
            return commDimBoList.get(0);
        }
        return null;
    }

    public void removeGrgDim(String TblCommId) {
        tblCommDimDAO.deleteTblCommDim(TblCommId);
    }

    public Map<String, Object> findCommListPage(Map param) {
        String whereClause = "1=1 ";

        TblUserDimBo userBo = IUserService.currentUser();

        String commCode = MapUtils.getString(param, "commCode", "");
        if(StringUtils.isNotEmpty(commCode)){
            whereClause += " and comm_code = '"+commCode+"'";
        }
        else if (!SecurityUtils.getSubject().hasRole(Global.ROLE_SUPPER_ADMIN)) {
            whereClause += " and comm_code in (" + IUserService.getUserCommsSqlStr(userBo) + ")";
        }

        String strCommName = MapUtils.getString(param, "commName", "");
        if (StringUtils.isNotEmpty(strCommName)) {
            whereClause += " and comm_name like '%" + strCommName + "%'";
        }

        String commState = MapUtils.getString(param, "commState", "");
        if (StringUtils.isNotEmpty(commState)) {
            whereClause += " and comm_state = '"+commState+"'";
        }

        String sql = "select * from tbl_comm_dim where " + whereClause;
        sql += " order by comm_code asc";
        Map<String, Object> result = new HashMap<String, Object>();
        Page p = BaseDao.queryPage(sql, Map.class);
        result.put("list", p.getList());
        result.put("size", p.getTotalNumber());
        result.put("ret_code", 1);
        return result;
    }

    @Override
    public List<TblCommDimBo> findCommList(Map param) throws Exception {
        String where = " where 1=1 ";

        String commName = MapUtils.getString(param, "commName", "");
        if (commName != null && StringUtils.isNotEmpty(commName)) {
            where += " and comm_name like '%" + commName + "%'";
        }

        TblUserDimBo userInfo = IUserService.currentUser();
        /* 只有cms角色账号，才需要默认小区 */
        if(!Global.ROLE_SUPPER_ADMIN_CMS.equals(userInfo.getRoleName()))
            where += " and comm_code != '"+Global.DEFAULT_COMM+"'";

        if (SecurityUtils.getSubject().hasRole(Global.ROLE_SUPPER_ADMIN)) {
            return findTblCommDimByWhere(where);
        } else {
            String commWhere = IUserService.getUserCommsSqlStr(userInfo);
            where += " and comm_code in (" + commWhere + ")";
            return findTblCommDimByWhere(where);
        }
    }

    /**
     * @param commName 小区名
     * @param city     城市名
     * @return
     * @throws Exception
     */
    @Override
    public TblCommDimBo getCommDimBoByCommName(String commName, String city) throws Exception {
        TblCommDimBo commDimBo = null;
        List<TblCommDimBo> commDimBos = findTblCommDimByWhere(
                "where 1=1 and comm_name = '" + commName + "'");
        if (commDimBos.size() > 1) {
            for (TblCommDimBo bo : commDimBos) {
                if (bo.getCity().contains(city)) {
                    commDimBo = bo;
                    break;
                }
            }
        } else if (commDimBos.size() == 1) {
            commDimBo = commDimBos.get(0);
        }
        return commDimBo;
    }

    /**
     * 针对用户角色生成这个小区对应的设备列表
     * @param role
     * @param bindingRoom
     * @return
     * @throws Exception
     */
    public List<UserDevice> genDeviceListForRole(String role, String bindingRoom) throws Exception{
        String commCode = AccountsUtils.getCommCode(bindingRoom);
        String where = "where 1=1 and comm_code = '" + commCode + "'";
        List<UserDevice> devicesList = new ArrayList<>();
        TblCommDimBo comm = findTblCommDimById(commCode);

        if(role.equals(OwnerConstant.ROLE_MANAGER_TYPE)) {
            List<TblBuildingDimBo> bos = IBuildingService.findTblBuildingDimByWhere(where);

            for (TblBuildingDimBo tblBuildingDimBo : bos) {

                String areaAliasName = tblBuildingDimBo.getAreaAliasName();
                int devNumber = tblBuildingDimBo.getDevNumber();

                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(commCode);
                stringBuilder.append(AccountsUtils.appendZeroBuilding(tblBuildingDimBo.getAreaName()));
                stringBuilder.append(AccountsUtils.appendZeroBuilding(tblBuildingDimBo.getBuildingName()));

                for (int i = 0; i < devNumber; i++) {
                    String devNum = String.valueOf(i + 1);
                    String sipNum = stringBuilder.toString() + "000" + devNum;
                    if (com.jhws.util.StringUtils.isEmpty(areaAliasName)) {
                        devicesList.add(new UserDevice(sipNum, AccountsUtils.getUnitInfo(sipNum) + ":门口机-" + devNum));
                    } else {
                        devicesList.add(new UserDevice(sipNum, areaAliasName + AccountsUtils.getUnit(sipNum) + "单元:门口机-" + devNum));
                    }
                }
            }

            int gateDevNum = comm.getGateDevNum();
            if (gateDevNum > 0) {
                for (int i = 0; i < gateDevNum; i++) {
                    UserDevice devices = new UserDevice();
                    String sipNum = commCode + "0000000" + (char) ('a' + i);
                    devicesList.add(new UserDevice(sipNum,commUtil.getGateDevAliasName(sipNum, comm.getGateDevAliasName())));
                }
            }
        }else if(role.equals(OwnerConstant.ROLE_OWNER_TYPE)){
            /* 添加门口机设备开锁监视绑定关系 */
            int device_number = IBuildingService.getUnitDevNumber(bindingRoom);
            for (int i = 1; i <= device_number; i++) {
                devicesList.add(new UserDevice(bindingRoom.substring(0, 8) + "000" + i,"门口机-"+i));
            }

            for (int i = 0; comm != null && i < comm.getGateDevNum(); i++) {
                String sipNum = commCode + "0000000" + (char) ('a' + i);
                devicesList.add(new UserDevice(sipNum,commUtil.getGateDevAliasName(sipNum, comm.getGateDevAliasName())));
            }

        }

        return devicesList;

    }
}
